package resolver

import (
	"gitee.com/xuxusheng/be-order/model"
	"github.com/graphql-go/graphql"
	"log"
)

var phone = graphql.NewObject(graphql.ObjectConfig{
	Description: "电话信息",
	Name:        "Phone",
	Fields: graphql.Fields{
		"id": &graphql.Field{
			Description: "电话信息ID",
			Type:        graphql.Int,
		},
		"tel": &graphql.Field{
			Description: "电话号码",
			Type:        graphql.String,
		},
	},
})

var createPhoneField = &graphql.Field{
	Description: "创建电话",
	Type:        graphql.Boolean,
	Args: graphql.FieldConfigArgument{
		"customerId": &graphql.ArgumentConfig{
			Description: "客户ID",
			Type:        graphql.NewNonNull(graphql.Int),
		},
		"tel": &graphql.ArgumentConfig{
			Description: "电话号码",
			Type:        graphql.NewNonNull(graphql.String),
		},
	},
	Resolve: createPhone,
}

var deletePhoneField = &graphql.Field{
	Description: "删除电话",
	Type:        graphql.Boolean,
	Args: graphql.FieldConfigArgument{
		"ids": &graphql.ArgumentConfig{
			Description: "电话ID数组",
			Type:        graphql.NewNonNull(graphql.NewList(graphql.NewNonNull(graphql.Int))),
		},
	},
	Resolve: deletePhone,
}

var updatePhoneField = &graphql.Field{
	Description: "更新电话",
	Type:        graphql.Boolean,
	Args: graphql.FieldConfigArgument{
		"id": &graphql.ArgumentConfig{
			Description: "ID",
			Type:        graphql.NewNonNull(graphql.Int),
		},
		"tel": &graphql.ArgumentConfig{
			Description: "电话号码",
			Type:        graphql.NewNonNull(graphql.String),
		},
	},
	Resolve: updatePhone,
}

func createPhone(p graphql.ResolveParams) (interface{}, error) {
	customerId := p.Args["customerId"].(int)
	tel := p.Args["tel"].(string)
	phone := model.Phone{
		CustomerId: int64(customerId),
		Tel:        tel,
	}
	_, err := phone.Create()
	if err != nil {
		log.Printf("[resovler 创建电话] failed: %v", err)
		return false, err
	}
	return true, nil
}

func deletePhone(p graphql.ResolveParams) (interface{}, error) {
	ids := p.Args["ids"].([]interface{})
	var iIds []int
	for _, v := range ids {
		iIds = append(iIds, v.(int))
	}

	phone := model.Phone{}
	err := phone.DeleteMulti(iIds)
	if err != nil {
		log.Printf("[resolver 删除电话] failed: %v", err)
		return false, err
	}
	return true, nil
}

func updatePhone(p graphql.ResolveParams) (interface{}, error) {

	return true, nil
}
